import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 如果已经明确设置了 Authorization header，则不覆盖
    if (!config.headers.Authorization) {
      // 优先使用 doctorToken，如果为空或不存在则使用 adminToken
      let token = localStorage.getItem('doctorToken')
      if (!token || token.trim() === '') {
        token = localStorage.getItem('adminToken')
      }
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('doctorToken')
      localStorage.removeItem('adminToken')
      localStorage.removeItem('level')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// ==================== 医生基础功能 ====================

// 获取医院列表
export const getHospitals = () => {
  return api.get('/doctor/hospitals')
}

// 医生注册
export const doctorRegister = (data) => {
  return api.post('/doctor/register', data)
}

// 医生登录
export const doctorLogin = (data) => {
  return api.post('/doctor/login', data)
}

// 医生信息更新
export const updateDoctorInfo = (data) => {
  return api.put('/doctor/update', data)
}

// 发送邮箱验证码
export const sendEmailCode = (data) => {
  return api.post('/doctor/sendEmailCode', data)
}

// 密码重置
export const resetPassword = (data) => {
  return api.post('/doctor/resetPassword', data)
}

// 获取医生信息
export const getDoctorInfo = () => {
  return api.get('/doctor/info')
}

// 根据用户名获取医生信息（密码找回用）
export const getDoctorInfoForReset = (username) => {
  return api.get('/doctor/getDoctorInfoForReset', { params: { username } })
}

// 根据用户名获取邮箱（密码找回用）
export const getEmailByUsername = (username) => {
  return api.get('/doctor/getEmailByUsername', { params: { username } })
}

// 验证邮箱验证码
export const verifyEmailCode = (data) => {
  return api.post('/doctor/verifyEmailCode', data)
}

// 上传头像
export const uploadAvatar = (formData) => {
  return api.post('/doctor/uploadAvatar', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取医生头像URL
export const getDoctorAvatar = (doctorId) => {
  return api.get(`/doctor/${doctorId}/avatar`)
}

// 获取当前登录医生的头像URL
export const getCurrentDoctorAvatar = () => {
  return api.get('/doctor/avatar')
}

// ==================== 医生管理功能（管理员专用） ====================

// 管理员查询医生
export const getDoctorsByAdmin = (data) => {
  // 管理员接口必须使用 adminToken
  const adminToken = localStorage.getItem('adminToken')
  if (!adminToken) {
    return Promise.reject(new Error('需要管理员权限'))
  }
  
  return api.post('/admin/doctors', data, {
    headers: {
      Authorization: `Bearer ${adminToken}`
    }
  })
}

// 管理员删除医生
export const deleteDoctorByAdmin = (doctorId) => {
  // 管理员接口必须使用 adminToken
  const adminToken = localStorage.getItem('adminToken')
  if (!adminToken) {
    return Promise.reject(new Error('需要管理员权限'))
  }
  
  return api.delete(`/admin/doctors/${doctorId}`, {
    headers: {
      Authorization: `Bearer ${adminToken}`
    }
  })
}

// 创建医生
export const createDoctor = (data) => {
  return api.post('/doctor-manage/create', data)
}

// 更新医生信息
export const updateDoctor = (data) => {
  return api.put('/doctor-manage/update', data)
}

// 软删除医生
export const deleteDoctor = (doctorId) => {
  return api.delete(`/doctor-manage/delete/${doctorId}`)
}

// 批量软删除医生
export const batchDeleteDoctor = (doctorIds) => {
  return api.delete('/doctor-manage/batch-delete', { data: doctorIds })
}

// 恢复已删除的医生
export const restoreDoctor = (doctorId) => {
  return api.put(`/doctor-manage/restore/${doctorId}`)
}

// 分页查询医生
export const getDoctorPage = (queryDTO, pageDTO) => {
  return api.post('/doctor-manage/page', { queryDTO, pageDTO })
}

// 分页查询已删除的医生
export const getDeletedDoctorsPage = (pageDTO) => {
  return api.get('/doctor-manage/deleted/page', { params: pageDTO })
}

// 查询医生详情
export const getDoctorDetail = (doctorId) => {
  return api.get(`/doctor-manage/detail/${doctorId}`)
}

// 获取已删除医生列表
export const getDeletedDoctorsList = () => {
  return api.get('/doctor-manage/deleted/list')
}

// 统计已删除医生总数
export const getDeletedDoctorsCount = () => {
  return api.get('/doctor-manage/deleted/count')
}

// ==================== 医生活动报名功能 ====================

// 获取可报名的活动列表
export const getAvailableActivities = (params = {}) => {
  return api.get('/doctor/activity/available', { 
    params: {
      current: params.current || 1,
      size: params.size || 10
    }
  })
}

// 获取已报名的活动列表
export const getRegisteredActivities = (params = {}) => {
  return api.get('/doctor/activity/registered', { 
    params: {
      current: params.current || 1,
      size: params.size || 10
    }
  })
}

// 报名活动
export const registerActivity = (activityId, data) => {
  return api.post(`/doctor/activity/register/${activityId}`, data)
}

// 取消报名
export const cancelActivityRegistration = (activityId) => {
  return api.post(`/doctor/activity/cancel/${activityId}`)
}

// 获取参加活动数量统计
export const getAttendedActivitiesCount = () => {
  return api.get('/doctor/activity/attended/count')
}

// 获取总积分
export const getTotalPoints = () => {
  return api.get('/doctor/activity/points/total')
}

// 获取医生工作统计信息
export const getDoctorWorkStatistics = () => {
  return api.get('/doctor/activity/work-statistics')
}

// ==================== 健康档案管理功能 ====================

// 获取所有就诊人列表（分页）
export const getPatientList = (params = {}) => {
  return api.get('/patient/admin/list-all', { 
    params: {
      current: params.current || 1,
      size: params.size || 10
    }
  })
}

// 根据ID获取就诊人完整信息
export const getPatientById = (id) => {
  return api.get(`/patient/admin/${id}`)
}

// 修改就诊人健康指标
export const updatePatientHealth = (data) => {
  return api.put('/patient/admin/update-health', data)
}

// 更新健康档案
export const updateHealthRecord = (data) => {
  return api.put('/doctor/health-record/update', data)
}

// ==================== 健康数据统计功能 ====================

// 获取健康统计数据
export const getHealthStatistics = (params = {}) => {
  return api.get('/doctor/health-statistics', { params })
}

// 获取患者健康数据（分页）
export const getPatientHealthData = (params = {}) => {
  return api.get('/doctor/patient-health-data', { params })
} 